<?php


namespace App\Repositories;


use App\Services\Tools\DateTime;
use Illuminate\Support\Facades\DB;

class StatisticsRepository
{
    //获取平台汇总数据
    public function getPlatformSummaryData($param)
    {
        $dateTag = $param['date_tag'] ?? 1;
        $startDate = $param['sd_start_date'] ?? '';
        $endDate = $param['sd_end_date'] ?? '';

        $date = DateTime::getDateRangeByTag($dateTag, $startDate, $endDate);

        $data = app('model_platform_everyday_data')
            ->select(DB::raw(app('model_platform_everyday_data')->formatFieldsWithSum()))
            ->where(function ($query) use ($date) {
                if (is_array($date)) {
                    $query->whereBetween('date', $date);
                } else {
                    $query->where('date', $date);
                }
            })
            ->first();
        return $data;
    }

    //获取平台每日数据
    public function getPlatformDayData($param, $isPaging = 1)
    {
        $startDate = $param['start_date'] ?? '';
        $endDate = $param['end_date'] ?? '';
        $newOldUser = $param['new_old_user'] ?? -1;
        $channelId = $param['channel_id'] ?? -1;
        $channelStageId = $param['channel_stage_id'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($startDate) {
            $where[] = ['date', '>=', $startDate];
        }
        if ($endDate) {
            $where[] = ['date', '<=', $endDate];
        }
        if ($newOldUser == 1) {
            $where[] = ['is_new_user', '=', 1];
        } else if ($newOldUser == 2) {
            $where[] = ['is_new_user', '=', 0];
        }
        if ($channelId > -1) {
            $where[] = ['channel_id', '=', $channelId];
        }
        if ($channelStageId > -1) {
            $where[] = ['channel_stage_id', '=', $channelStageId];
        }

        $data = app('model_platform_everyday_data')
            ->select('date', DB::raw(app('model_platform_everyday_data')->formatFieldsWithSum()))
            ->where($where)
            ->groupBy('date');
        if ($isPaging == 1) {
            $data = $data->paginate($pageSize);
        } else {
            $data = $data->get()->toArray();
        }

        return $data;
    }

    //观看直播总时长
    public function watchLiveDuration($userId)
    {
        $data = app('model_room_join_time')
            ->select(DB::raw('sum(left_time-join_time) as watch_live_seconds'))
            ->where('user_id', $userId)
            ->first();
        if ($data) {
            return round($data->watch_live_seconds/3600, 1);
        } else {
            return 0;
        }
    }
}